package hw.ats.news.model;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 카테고리
 * @author pcraft
 */
public class Cate {
	public int uid = 0;
	public int pid = 0;
	public String title = "";
	public String icon = "";
	public String navicon = "";
	public int order_no = 0;
	public boolean navi_flag = false;
	
	public Cate() {
	}
	
	public Cate(int uid, String title, int order_no) {
		this.uid = uid;
		this.title = title;
		this.icon = "";
		this.navicon = "";
		this.order_no = order_no;
		this.navi_flag = false;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("uid=").append(uid).append(", ");
		sb.append("pid=").append(pid).append(", ");
		sb.append("title=").append(title).append(", ");
		sb.append("icon=").append(icon);
		return sb.toString();
	}
	
	private Cate bind(Cursor c) {
		this.uid = c.getInt(c.getColumnIndex("uid"));
		this.title = c.getString(c.getColumnIndex("title"));
		this.icon = c.getString(c.getColumnIndex("icon"));
		this.navicon = c.getString(c.getColumnIndex("navicon"));
		this.order_no = c.getInt(c.getColumnIndex("order_no"));
		this.navi_flag = c.getInt(c.getColumnIndex("navi_flag")) > 0;
		return this;
	}
	
	public static Cate load(SQLiteDatabase db, int uid) {
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM cate WHERE uid = " + uid, null);
			if (!c.moveToFirst()) {
				return null;
			}

			return new Cate().bind(c);
		} finally {
			try { c.close(); } catch (Exception ignored) {}
		}
	}
	
	public static List<Cate> list(SQLiteDatabase db) {
		List<Cate> list = new ArrayList<Cate>();
		Cursor c = null;
		try {
			c = db.rawQuery("SELECT * FROM cate ORDER BY uid", null);
			if (!c.moveToFirst()) {
				return list;
			}

			do {
				Cate entry = new Cate();
				entry.bind(c);
				list.add(entry);
			} while (c.moveToNext());
		} finally {
			try { c.close(); } catch (Exception ignored) {}
		}
		
		return list;
	}
	
	public void insert(SQLiteDatabase db) {
		try {
			ContentValues v = new ContentValues();
			v.put("uid", uid);
			v.put("title", title);
			v.put("icon", icon);
			v.put("navicon", navicon);
			v.put("order_no", order_no);
			v.put("navi_flag", navi_flag ? 1 : 0);
			db.insert("cate", null, v);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
	
	public void update(SQLiteDatabase db) {
		try {
			ContentValues v = new ContentValues();
			v.put("title", title);
			v.put("icon", icon);
			v.put("navicon", navicon);
			v.put("order_no", order_no);
			v.put("navi_flag", navi_flag ? 1 : 0);
			db.update("cate", v, "uid="+uid, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
}
